package edu.bit.water.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import edu.bit.water.dao.WbalChartDao;
import edu.bit.water.entity.Chart;

@Service
public class WbalChartService {
	
	@Autowired
	WbalChartDao wbalChartDao;

	/**
	 * 增加流程图相关数据的方法
	 * @param chart 流程图实体类
	 * @return 成功返回1,失败返回0
	 */
	public Map<String, String> addChart(Chart chart) {
		Map<String, String> map = new HashMap<>();
		Integer id = wbalChartDao.getMaxId();
		if(id == null) {
			chart.setId(0);
		}else {
			chart.setId(id + 1);
		}
		try{
			wbalChartDao.addChart(chart);
			map.put("status", "success");
		}catch (DuplicateKeyException e){
			map=updateChart(chart);
		}
		return map;
	}
	
	/**
	 * 修改某个流程图数据
	 * @param chart 将要被修改的流程图数据
	 * @return 成功返回1,失败返回0
	 */
	public Map<String, String> updateChart(Chart chart) {
		Map<String, String> map = new HashMap<>();
		try {
			int n = wbalChartDao.updateChart(chart);
			if(n == 1) {
				map.put("status", "success");
			}else {
				map.put("status", "failed");
			}
			return map;
		}catch (DuplicateKeyException e) {
			e.printStackTrace();
		}
		return map;
	}

	public Chart selectOne(int id) {
		return wbalChartDao.selectOne(id);
	}

	public List<Chart> selectChartByBusiness(int businessId) {return wbalChartDao.selectChartByBusiness(businessId);}

	/**
	 * 删除流程图的方法
	 * @param idList 将要被删除id的list集合
	 * @return 成功返回1,失败返回0
	 */
	public int deleteChart(List<Integer> idList) {
		try {
			for (int id : idList) {
				wbalChartDao.deleteChart(id);
			}
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return 0;
		}
	}

}
